package cn.hc.case3;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author huangchao E-mail:fengquan8866@163.com
 * @version 创建时间：2024/10/19 11:51
 */
public class CuratorLockTest {
    // 注意：逗号左右不能有空格
    private static String connectString = "master:2181,hadoop141:2181,hadoop-test:2181";
    private static int sessionTimeout = 2000;

    public static void main(String[] args) {
        // 创建分布式锁1
        InterProcessMutex lock1 = new InterProcessMutex(getCuratorFramework(), "/hc/locks");
        // 创建分布式锁2
        InterProcessMutex lock2 = new InterProcessMutex(getCuratorFramework(), "/hc/locks");

        new Thread(() -> {
            try {
                lock1.acquire();
                System.out.println("Thread1 get lock1");

                lock1.acquire();
                System.out.println("Thread1 再次get lock1");

                Thread.sleep(5000);

                lock1.release();
                System.out.println("Thread1 release lock1");

                lock1.release();
                System.out.println("Thread1 再次release lock1");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(() -> {
            try {
                lock2.acquire();
                System.out.println("Thread1 get lock2");

                lock2.acquire();
                System.out.println("Thread1 再次get lock2");

                Thread.sleep(5000);

                lock2.release();
                System.out.println("Thread1 release lock2");

                lock2.release();
                System.out.println("Thread1 再次release lock2");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();


    }

    private static CuratorFramework getCuratorFramework() {

        ExponentialBackoffRetry policy = new ExponentialBackoffRetry(3000, 3);

        CuratorFramework client = CuratorFrameworkFactory.builder().connectString(connectString)
                .connectionTimeoutMs(sessionTimeout)
                .sessionTimeoutMs(sessionTimeout)
                .retryPolicy(policy)
                .build();
        // 启动客户端
        client.start();

        System.out.println("zookeeper client started");
        return client;
    }
}
